use std::os::windows::ffi::OsStrExt;
use std::{fs::File, io::Read};
use std::io::copy;
use std::path::PathBuf;
use dirs::picture_dir;
use reqwest::blocking::get;

use winapi::um::winuser::SystemParametersInfoW;

fn download_image(url: &str, save_path: &PathBuf) -> Result<(), Box<dyn std::error::Error>> {
    let response = get(url)?;
    let mut out = File::create(save_path)?;
    copy(&mut response.take(10_000_000), &mut out)?; // limit to 10MB
    Ok(())
}

fn set_wallpaper(image_path: &PathBuf) -> Result<(), Box<dyn std::error::Error>> {
    let image_path_wide: Vec<u16> = image_path.as_os_str().encode_wide().chain(Some(0)).collect();
    unsafe {
        SystemParametersInfoW(
            0x0014,
            0,
            image_path_wide.as_ptr() as *mut _,
            0x0001,
        );
    }
    Ok(())
}

pub(crate) fn maldev_wallpaper(){
    let url = "https://raw.githubusercontent.com/Whitecat18/Whitecat18/main/files/encrypt.png";
    
    let mut save_path = picture_dir().unwrap_or_else(|| PathBuf::from("C:/Windows/Temp"));
    save_path.push("encrypt.png");
    
    download_image(url, &save_path).expect("Error");
    set_wallpaper(&save_path).expect("Error");

    println!("Wallpaper set successfully!");
}
